package com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.HddcB3DrillprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.HddcB3DrillprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.entity.HddcB3DrillprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.HddcB3DrillprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.viewobjects.HddcB3DrillprojecttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.viewobjects.HddcB3DrillprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.viewobjects.HddcB3DrillprojecttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB3DrillprojecttableServiceImpl implements HddcB3DrillprojecttableService {

    private final HddcB3DrillprojecttableRepository hddcB3DrillprojecttableRepository;
    private final HddcB3DrillprojecttableNativeRepository hddcB3DrillprojecttableNativeRepository;
    private final DrillingEngineeringTableExcelVerifyHandler drillingEngineeringTableExcelVerifyHandler;

    @Autowired
    public HddcB3DrillprojecttableServiceImpl(HddcB3DrillprojecttableRepository hddcB3DrillprojecttableRepository,
                                              HddcB3DrillprojecttableNativeRepository hddcB3DrillprojecttableNativeRepository,
                                              DrillingEngineeringTableExcelVerifyHandler drillingEngineeringTableExcelVerifyHandler) {
        this.hddcB3DrillprojecttableRepository = hddcB3DrillprojecttableRepository;
        this.hddcB3DrillprojecttableNativeRepository = hddcB3DrillprojecttableNativeRepository;
        this.drillingEngineeringTableExcelVerifyHandler = drillingEngineeringTableExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB3Drillprojecttables(HddcB3DrillprojecttableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB3DrillprojecttablePageVO> hddcB3DrillprojecttablePage = this.hddcB3DrillprojecttableNativeRepository.queryHddcB3Drillprojecttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB3DrillprojecttablePage);
    }

    @Override
    public HddcB3DrillprojecttableEntity getHddcB3Drillprojecttable(String id) {
        return this.hddcB3DrillprojecttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB3DrillprojecttableEntity saveHddcB3Drillprojecttable(HddcB3DrillprojecttableEntity hddcB3Drillprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB3Drillprojecttable.setUuid(uuid);
        hddcB3Drillprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB3Drillprojecttable.setCreateTime(now);
        hddcB3Drillprojecttable.setUpdateTime(now);
        hddcB3Drillprojecttable.setIsValid(PlatformConstants.Y);
        hddcB3Drillprojecttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB3Drillprojecttable.setExtends10(PlatformConstants.Y);
        this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
        return hddcB3Drillprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB3DrillprojecttableEntity updateHddcB3Drillprojecttable(HddcB3DrillprojecttableEntity hddcB3Drillprojecttable) {
        HddcB3DrillprojecttableEntity entity = hddcB3DrillprojecttableRepository.findById(hddcB3Drillprojecttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcB3Drillprojecttable);
        hddcB3Drillprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB3Drillprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
        return hddcB3Drillprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB3Drillprojecttables(List<String> ids) {
        List<HddcB3DrillprojecttableEntity> hddcB3DrillprojecttableList = this.hddcB3DrillprojecttableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB3DrillprojecttableList) && hddcB3DrillprojecttableList.size() > 0) {
            for (HddcB3DrillprojecttableEntity hddcB3Drillprojecttable : hddcB3DrillprojecttableList) {
//                this.hddcB3DrillprojecttableRepository.delete(hddcB3Drillprojecttable);
                hddcB3Drillprojecttable.setIsValid(PlatformConstants.N);
                hddcB3Drillprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB3Drillprojecttable.setUpdateTime(new Date());
                this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB3DrillprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB3DrillprojecttableEntity> yhDisasterEntities = hddcB3DrillprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB3DrillprojecttableVO> list = new ArrayList<>();
        for (HddcB3DrillprojecttableEntity entity : yhDisasterEntities) {
            HddcB3DrillprojecttableVO yhDisasterVO = new HddcB3DrillprojecttableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "钻探工程表", "钻探工程表",
                HddcB3DrillprojecttableVO.class, "钻探工程表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(drillingEngineeringTableExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB3DrillprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB3DrillprojecttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB3DrillprojecttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB3DrillprojecttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB3DrillprojecttableVO> list) {
        for (HddcB3DrillprojecttableVO hddcB3DrillprojecttableVO : list) {
            HddcB3DrillprojecttableEntity yhDisasterEntity = new HddcB3DrillprojecttableEntity();
            BeanUtils.copyProperties(hddcB3DrillprojecttableVO, yhDisasterEntity);
            saveHddcB3Drillprojecttable(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB3DrillprojecttableEntity> hddcDataList = this.hddcB3DrillprojecttableRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB3DrillprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB3DrillprojecttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB3DrillprojecttableEntity> hddcDataList = this.hddcB3DrillprojecttableRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB3DrillprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB3DrillprojecttableRepository.save(entity);
            }
        }
    }
}
